<template>
  <div
    :id="'chartMain' + chartId"
    v-loading="isVisualVappShowLoadingProgress && isLoading"
    class="chartMain multi-single-icon"
    :class="`${componentStyleClass} ${componentStyle}-Style`"
  >
    <Tooltip ref="Tooltip" :component-style="componentStyle" />
    <AdvancedLinkageToolbar :wid="widgetInstanceId" :config="config" />
    <ComponentTitle :property="config.config.property" :title-text-style="getCssStyle('title')" />
    <div
      v-show="!isNoData && !isDataAbnormal"
      class="displayBox"
      :style="{
        ...getCssStyle('grid'),
        ...boxBgColor,
        height: title ? 'calc(100% - ' + getCssStyle('title').lineHeight + ')' : '100%',
      }"
    >
      <div class="displayBox-main">
        <div
          v-for="(item, index) in showData"
          :key="index"
          v-visual-tooltip="getTooltip(item)"
          :class="
            `multi-single-contentBox multi-single-icon-contentBox${chartId}
            ${config.config.property.selectedStatus ? 'contentData-hover' : ''} ${
              selectedIndex === index && config.config.property.selectedStatus ? 'on' : ''
            }`
          "
          :style="itemStyle"
          @click="emitAllMessages(item, index)"
        >
          <div :class="`contentData`">
            <div class="img" :style="style.img">
              <Icon v-if="haveIcon(item.icon)" :conf="item.icon" />
              <el-image v-else :src="getImg(item, index)" :style="style.elImage">
                <template #placeholder>
                  <div class="image-slot">
                    {{ $demoi18n('message.loading') }}
                    <span class="dot">...</span>
                  </div>
                </template>
                <template #error>
                  <div></div>
                </template>
              </el-image>
            </div>
            <div class="text" :style="style.text">
              <span class="value" :style="{ ...(item.style ? item.style.value : {}), ...multiValStyle(item) }">
                {{ item.value }}
              </span>
              <span
                class="unit"
                :style="{
                  ...(item.style ? item.style.unit : {}),
                  ...getCssStyle('unit'),
                  ...multiValStyle(item, 'unit'),
                }"
              >
                {{ item.unit }}
              </span>
            </div>

            <div class="contentName" :style="style.contentName" :title="item.alias ? item.alias : item.name">
              <span class="name" :style="getCssStyle('name')">
                {{ item.alias ? item.alias : item.name }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <NoData
      :isNoData="isNoData"
      :boxBgColor="boxBgColor"
      :noDataPromptType="config.config.property.noDataPromptType"
      :noDataPrompt="config.config.property.noDataPrompt"
    />
    <AbnormalData :isDataAbnormal="isDataAbnormal" :boxBgColor="boxBgColor" :abnormalType="abnormalType" />
  </div>
</template>
<script>
import AdvancedLinkageToolbar from '@/components/common/advanced-linkage/advanced-linkage-toolbar.vue';
import Icon from '@/components/common/icon/icon.vue';
import colorGroup from '@/components/panel-property-multi-value/colorGroup';
import dfCssStyle from '@/components/panel-property-multi-value/cssStyle-default.js';
import chartBase from '@/mixin/chart-base.js';
import componentValueBase from '@/mixin/component-value-base.js';
import iconChartBase from '@/mixin/icon-chart-base.js';
import { convertValue } from '@/utils/util.js';
import ComponentTitle from '../common/component-title/component-title.vue';
import NoData from '../common/no-data/no-data.vue';
import AbnormalData from '../common/abnormal-data/abnormal-data.vue';
import Tooltip from '../common/tooltip/tooltip.vue';
import config from './config/config';
import { nextTick } from 'vue';

export default {
  name: 'MultiValueSingleLineWithIcon',
  components: { ComponentTitle, NoData, Tooltip, Icon, AdvancedLinkageToolbar, AbnormalData },
  mixins: [chartBase, iconChartBase, componentValueBase],
  props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h'],
  data() {
    const _config = JSON.parse(JSON.stringify(config));
    return {
      ..._config.config.property,
      isIcon: true,
      isLoading: false,
      isNoData: false,
      selectedIndex: -1,
      orgConfig: [],
      chartId: '',
      config: null,
      title: '',
      configData: [],
      showData: [],
      isThreshold: false,
      threshold: [],
      count: 0,
      isDynamicAdapt: false,
      style: {
        light: {
          box: { backgroundColor: '#FFF', borderTop: '' },
          back: { backgroundColor: '#F5FAFF' },
        },
        dark: {
          box: { backgroundColor: '#0D263A', borderTop: '' },
          back: { backgroundColor: '#122E45' },
        },
        real: {
          box: { backgroundColor: '#232323', borderTop: '' },
          back: { backgroundColor: '#122E45' },
        },
        displayBox: {},
        img: {},
        elImage: {},
        text: {},
        contentName: {},
      },
      componentStyle: window._adoPremise.uc.theme,
      colorGroup: colorGroup,
      titleHeight: 0,
      imgSize: 60,
      dfCssStyle,
    };
  },
  computed: {
    itemStyle() {
      const bgColorMap = {
        light: '#F5FAFF',
        dark: '#122E45',
        real: '#303030',
      };
      const bgColor = bgColorMap[this.componentStyle];
      const { backgroundColor } = this.config.config.property || this.getValByCompStl('#ffffff', '#0D263A', '#303030');
      const { unitGap } = this.config.config.property || 0;
      const n = this.showData.length;
      const originBgColors = ['#fff', '#ffffff', '#0d263a', '#232323'];

      let boxBgColor;
      if (backgroundColor) {
        if (originBgColors.includes(backgroundColor.toLowerCase())) {
          boxBgColor = bgColor;
        } else {
          boxBgColor = backgroundColor;
        }
      } else {
        boxBgColor = bgColor;
      }
      return {
        backgroundColor: boxBgColor,
        marginRight: `${unitGap}px`,
      };
    },
  },
  showData() {
    nextTick(() => {
      this.calcUnitRect();
    });
  },
  created() {
    this.orgConfig = config;
    this.config = JSON.parse(JSON.stringify(this.orgConfig));

    this.chartId = `${this.widgetInstanceId}_01`;
  },
  mounted() {
    if (window.isLocalEnv) {
      this.loadWidget();
    }
  },
  methods: {

    /**
     * 计算容器的最小宽高 实现自适应
     */
    async calcUnitRect() {
      this.calcing = true;
      const compnt = document.getElementById(`chartMain${this.chartId}`);
      if (!compnt) {
        return;
      }
      const contentBox = compnt.getElementsByClassName('displayBox-main')[0];
      const arrW = [];
      const arrH = [];
      contentBox.style = {};
      contentBox.style.minWidth = 'auto';
      contentBox.style.minHeight = 'auto';

      const units = compnt.getElementsByClassName('multi-single-contentBox');
      for (let i = 0; i < units.length; i++) {
        units[i].style.minWidth = 'auto';
        units[i].style.minHeight = 'auto';

        const contentData = units[i].getElementsByClassName('contentData')[0];
        if (contentData) {
          contentData.style.width = 'auto';
        }
      }

      for (let i = 0; i < units.length; i++) {
        const contentData = units[i].getElementsByClassName('contentData')[0];
        if (contentData) {
          const _img = contentData.querySelector('.img') || {};
          const text = contentData.querySelector('.text') || {};
          const contentName = contentData.querySelector('.contentName') || {};
          const imgH = _img.offsetHeight || 0;
          const textH = text.offsetHeight || 0;
          const nameH = contentName.offsetHeight || 0;
          arrW.push(contentData.offsetWidth);
          arrH.push(Math.ceil(imgH + textH + nameH));
        }
      }
      arrW.sort((a, b) => b - a);
      arrH.sort((a, b) => b - a);
      contentBox.style.minHeight = `${arrH[0]}px`;
      contentBox.style.minWidth = `${arrW[0] * this.showData.length}px`;

      this.calcing = false;
    },
    emitAllMessages(item, index) {
      this.selectedIndex = index;
      const mappingObj = {
        s: 'name',
        y: 'value',
      };
      this.sendAllMessages(item, index, mappingObj);
      this.sendAdvancedLinkagge({
        s: item.name,
        y: item.orgValue,
        unit: item.unit,
      });
    },
    selectItem(index) {
      const { selectedStatus } = this.config.config.property;
      if (!selectedStatus) {
        return;
      }
      if (this.selectedIndex === index) {
        return;
      }
      this.selectedIndex = index;
    },
    getImg(item, index, img = 'content') {
      const imgNum = 2;
      if (item.threImgUrl) {
        return item.threImgUrl;
      } else if (item.imgUrl) {
        return item.imgUrl;
      } else {
        return new URL(`../common/images/${img}_${this.componentStyle}_${index % imgNum}.png`, import.meta.url).href;
      }
    },

    // 初始加载时 以及 编排面更改配置时 触发
    loadWidget(pageStatus) {
      this.pageStatus = pageStatus;
      this._updateConfigProperty();
      this.updateComponentByResolution();
      this.updateConfigData();

      if (window.isLocalEnv || this.emitComponentStatus) {
        this.updateParams(pageStatus);
        if (!this.isRealTime) {
          this.debounceGetData();
        }
      }
      this.afterLoadWidget();
    },

    // 根据分辨率来更新组件
    updateComponentByResolution() {
      nextTick(() => {
        this.style.elImage.width = `${convertValue(this.imgSize)}px`;
        this.style.elImage.height = `${convertValue(this.imgSize)}px`;
        this.style = JSON.parse(JSON.stringify(this.style));

        setTimeout(() => {
          const title = document.querySelector(`#chartMain${this.chartId} .component-title`);
          this.titleHeight = title ? title.offsetHeight : 0;
          this.calcUnitRect();
        }, 500);
      });
    },
    _updateConfigProperty() {
      this.updateConfigProperty();
      const {
        data,
        isThreshold,
        threshold,
        title,
        componentStyle,
        isDynamicAdapt,
        imgSize = 60,
        multiSortBy = 'name',
      } = this.config.config.property;
      this.componentStyle = componentStyle;
      this.configData = JSON.parse(JSON.stringify(data));
      this.isThreshold = isThreshold;
      this.threshold = threshold;
      this.count = data.length;
      this.isDynamicAdapt = isDynamicAdapt;
      this.imgSize = imgSize;
      this.multiSortBy = multiSortBy;

      // 该方法在icon-chart-base.js里
      this.updateImgUrlMultiValue(this.configData);
    },
    getTooltip(item) {
      return {
        config: this.config.config.property.tooltip || {},
        vars: {
          s: item.name,
          y: item.value,
          unit: item.unit,
        },
        params: this.params,
        parentComp: this,
      };
    },
  },
};
</script>
<style lang="less" scoped>
// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
@import '../../common/chart.less';
</style>
<style lang="less" scoped>
@import './config/theme.less';
.multi-single-icon {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .title {
    width: 100%;
    height: 50px;
    font-size: 18px;
    position: relative;
    span {
      display: flex;
      align-items: center;
      height: 100%;
      margin-left: 5%;
    }
  }
  .displayBox {
    padding: 0 2.5%;
    height: 100%;
    flex: 1;
    margin: 0 auto;
    width: 100%;
    height: 100%;
    overflow: auto;
    text-align: center;
    overflow: auto;
    .displayBox-main {
      display: flex;
      white-space: nowrap;
      width: 100%;
      height: 100%;
      min-width: 100%;
      min-height: 100%;
      min-width: max-content;
      min-height: max-content;
      justify-content: space-around;
    }
    .contentData {
      display: flex;
      width: 100%;
      height: 100%;
      justify-content: space-around;
      flex-direction: column;
      .img {
        display: flex;
        justify-content: center;
        align-items: center;
        .el-image,
        .image-slot {
          width: 60px;
          height: 60px;
          vertical-align: middle;
        }
      }
      .text {
        white-space: nowrap;
        line-height: 1;
      }
      .contentName {
        line-height: 1.5;
        span {
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
.multi-single-contentBox {
  min-height: 100%;
  width: min-content;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  &.contentData-hover:hover {
    background-color: var(--contentData-hover-bg-color) !important;
  }
  &.on {
    background-color: var(--content-on-bg-color) !important;
  }
  .contentData {
    min-height: max-content;
    width: 100%;
    min-height: max-content;
    height: 100%;
    display: flex;
    justify-content: space-around;
    flex-wrap: nowrap;
    flex-direction: column;
  }
  &:last-child {
    margin-right: 0 !important;
  }
}
</style>
